﻿using System;
using System.Windows.Navigation;
using BathroomLocator.Phone.ViewModel;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Controls;

namespace BathroomLocator.Phone.Pages
{
	public partial class MainPage : PhoneApplicationPage
	{
		public MainPage()
		{
			InitializeComponent();

			var viewModel = new MainPageViewModel();
			this.DataContext = viewModel;

			this.BathroomListPage.ViewModel = viewModel.BathroomListPageViewModel;
			this.BathroomListPage.Navigate += this.OnNavigatePage;

			//this.MyBathroomsPage.ViewModel = viewModel.MyBathroomListPageViewModel;
		}

		protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
		{
			if (e.NavigationMode == NavigationMode.Back)
			{
				if (!GetApplicationState<bool>("UserLogout"))
				{
					// Save a flag to notify that the user wants to close the application.
					SetApplicationState("UserGoesBack", true);
				}
			}
		}

		private static T GetApplicationState<T>(string key)
		{
			if (!PhoneApplicationService.Current.State.ContainsKey(key))
			{
				return default(T);
			}

			return (T)PhoneApplicationService.Current.State[key];
		}

		private static void SetApplicationState(string key, object value)
		{
			if (PhoneApplicationService.Current.State.ContainsKey(key))
			{
				PhoneApplicationService.Current.State.Remove(key);
			}

			PhoneApplicationService.Current.State.Add(key, value);
		}

		private void OnMainPivotSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var currentView = (UserControl)((PivotItem)this.MainPivot.SelectedItem).Content;
			var viewModel = (PivotItemViewModel)currentView.DataContext;

			viewModel.UpdateApplicationBarButtons(this.ApplicationBar, new[] { "logout" });
		}

		private void OnNavigatePage(object sender, NavigationEventArgs e)
		{
			this.NavigationService.Navigate(e.Uri);
		}

		private void OnLogout(object sender, EventArgs e)
		{
			// Save a flag to notify that the user wants to close the application.
			SetApplicationState("UserLogout", true);

			this.NavigationService.GoBack();
		}
	}
}